// 提供复用逻辑的函数
import { useIntersectionObserver, useIntervalFn } from "@vueuse/core";
import { ref, onUnmounted } from "vue";
import dayjs from "dayjs";

// target 监听的DOM元素   apiFn api函数
export const useLazyData = (target, apiFn) => {
  const result = ref([]);
  //stop 停止观察
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }], observerElement) => {
      //isIntersecting表示是否进入可视区
      if (isIntersecting) {
        stop();
        //调用api函数获取数据

        apiFn().then((data) => {
          result.value = data.result;
        });
      }
    },
    //相交的阀值
    {
      threshold: 0,
    }
  );
  return result;
};

//封装倒计时的函数
export const usePayTime = () => {
  //倒计时功能
  const time = ref(0);
  const timeText = ref("");
  const { pause, resume } = useIntervalFn(
    () => {
      time.value--;
      timeText.value = dayjs.unix(time.value).format("mm分ss秒");
      if (time.value == 0) {
        pause();
      }
    },
    1000,
    false
  );
  onUnmounted(() => {
    pause();
  });
  //开启定时器
  const start = (countdown) => {
    time.value = countdown
    timeText.value = dayjs.unix(time.value).format("mm分ss秒");
    resume()
  }

  return {
    start,
    timeText
  }
};
